package com.gadgets.framework.advisor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gadgets.framework.annotation.IgnoreStandardResp;
import com.gadgets.framework.common.constant.ExceptionEnum;
import com.gadgets.framework.common.constant.GadgetsConstant;
import com.gadgets.framework.common.dto.HttpBaseResp;
import com.gadgets.framework.common.exception.GadgetsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;

/**
 * @author UncleXiu
 * @version V1.0.0
 * @data 2020-09-16
 *
 */
@RestControllerAdvice
public class CommonResponseDataAdvisor implements ResponseBodyAdvice<Object> {

    private static final Logger logger = LoggerFactory.getLogger(CommonResponseDataAdvisor.class);

    /**
     * Whether this component supports the given controller method return type
     * and the selected {@code HttpMessageConverter} type.
     *
     * @param returnType    the return type
     * @param converterType the selected converter type
     * @return {@code true} if {@link #beforeBodyWrite} should be invoked;
     * {@code false} otherwise
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        Method method = returnType.getMethod();
        if(null!=method){
            String typeName = method.getReturnType().getTypeName();
            if("java.lang.String".equals(typeName)){
                return false;
            }
            return !method.isAnnotationPresent(IgnoreStandardResp.class);
        }
        return true;
    }

    /**
     * Invoked after an {@code HttpMessageConverter} is selected and just before
     * its write method is invoked.
     *
     * @param body                  the body to be written
     * @param returnType            the return type of the controller method
     * @param selectedContentType   the content type selected through content negotiation
     * @param selectedConverterType the converter type selected to write to the response
     * @param request               the current request
     * @param response              the current response
     * @return the body that was passed in or a modified (possibly new) instance
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Object ret;
        if(null==body){
            // 如果是无返回，直接组建标准返回
            HttpBaseResp<Object> httpBaseResp = new HttpBaseResp<>();
            httpBaseResp.setRetCode(GadgetsConstant.RESP_CODE.SUCCESS_CODE);
            ret = httpBaseResp;
        } else if(body instanceof HttpBaseResp){
            // 如果是查询结果的赋值应答码直接返回
            if(StringUtils.isEmpty(((HttpBaseResp<?>) body).getRetCode())) {
                ((HttpBaseResp<?>) body).setRetCode(GadgetsConstant.RESP_CODE.SUCCESS_CODE);
            }
            ret = body;
        } else if(body instanceof ModelAndView){
            // 页面跳转的直接返回
            ret = body;
        } else {
            // 其他返回类型需要置换成JSON后返回
            HttpBaseResp<Object> httpBaseResp = new HttpBaseResp<>();
            httpBaseResp.setRetCode(GadgetsConstant.RESP_CODE.SUCCESS_CODE);
            if(body instanceof String){
                httpBaseResp.setErrorMsg((String) body);
            } else {
                httpBaseResp.setErrorMsg(JSON.toJSONString(body));
            }
            ret = httpBaseResp;
        }
        // INFO用于日志输出，日志分析使用
        logger.info("LOG-HTTP请求结束，应答信息：{}",JSON.toJSONString(ret));
        // DEBUG和控制台打印便于阅读
        logger.debug("LOG-HTTP请求结束，应答信息：{}",JSON.toJSONString(
                ret,
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat)
        );
        // 如果返回的 ContentType 不是 application/json ，那么就需要直接转成 JSON 字符串做返回
        if(!selectedContentType.equalsTypeAndSubtype(MediaType.APPLICATION_JSON)){
            return JSON.toJSONString(ret);
        }
        return ret;
    }

    /**
     * 统一异常处理器
     * @param t 异常信息
     * @return  应答信息
     */
    @ExceptionHandler(value = {Throwable.class})
    public HttpBaseResp<Object> handlerException(Throwable t){
        HttpBaseResp<Object> httpBaseResp = new HttpBaseResp<>();
        logger.error(com.gadgets.framework.common.util.StringUtils.formatExceptionStack(t));
        if(t instanceof GadgetsException){
            httpBaseResp.setErrorLevel(((GadgetsException) t).getErrorLevel());
            httpBaseResp.setRetCode(((GadgetsException) t).getErrorCode());
        }else {
            httpBaseResp.setRetCode(GadgetsConstant.RESP_CODE.NOT_KNOW_CODE);
            httpBaseResp.setErrorLevel(ExceptionEnum.BUSI_ERROR.getErrorLevel());
        }
        httpBaseResp.setErrorMsg(t.getMessage());
        logger.info("HTTP请求发生异常：{}",JSON.toJSONString(httpBaseResp));
        return httpBaseResp;
    }

}
